package com.wxm.china.port.dds.config;

import com.alibaba.fastjson.JSONObject;
import com.wxm.china.port.dds.utils.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 *      线程池配置
 * </p>
 *
 * @author: wxm
 * @Date: 2023/6/29
 */
@Slf4j
@Configuration
public class ThreadConfig {
    @Autowired
    private ThreadProperties properties;

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        log.info("{} 开始初始化线程池 -> {}", ConstantUtils.LOG_PREFIX, JSONObject.toJSONString(properties));
        try {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(
                    properties.getCorePoolSize(),
                    properties.getMaximumPoolSize(),
                    properties.getKeepAliveTime(),
                    properties.getUnit(),
                    new LinkedBlockingDeque<>(properties.getDequeCapacity()),
                    Executors.defaultThreadFactory(),
                    new ThreadPoolExecutor.AbortPolicy()
            );
            log.info("{} 初始化线程池成功", ConstantUtils.LOG_PREFIX);
            return executor;
        }catch (Exception e){
            log.error("{} 初始化线程池失败,请检查参数配置!", ConstantUtils.LOG_PREFIX,e);
            throw e;
        }
    }
}
